
var APP_DEBUG = true;

if (!window.console) {
    console = {
        log: function(ret) {
            // do something
        }
    };
}

function errorMessage(e) {
    console.log(e);
}

// tmpl function
!function(e) {
    "use strict";
    var n = function(e, t) {
        var r = /[^\w\-\.:]/.test(e) ? new Function(n.arg + ",tmpl", "var _e=tmpl.encode" + n.helper + ",_s='" + e.replace(n.regexp, n.func) + "';return _s;") : n.cache[e] = n.cache[e] || n(n.load(e));
        return t ? r(t, n) : function(e) {
            return r(e, n)
        }
    };
    n.cache = {}, n.load = function(e) {
        return document.getElementById(e).innerHTML
    }, n.regexp = /([\s'\\])(?![^%]*%\})|(?:\{%(=|#)([\s\S]+?)%\})|(\{%)|(%\})/g, n.func = function(e, n, t, r, c, u) {
        return n ? {"\n": "\\n", "\r": "\\r", "	": "\\t", " ": " "}[e] || "\\" + e : t ? "=" === t ? "'+_e(" + r + ")+'" : "'+" + r + "+'" : c ? "';" : u ? "_s+='" : void 0
    }, n.encReg = /[<>&"'\x00]/g, n.encMap = {"<": "<", ">": ">", "&": "&amp;", '"': "&quot;", "'": "&#39;"}, n.encode = function(e) {
        return String(e).replace(n.encReg, function(e) {
            return n.encMap[e] || ""
        })
    }, n.arg = "o", n.helper = ",print=function(s,e){_s+=e&&(s||'')||_e(s);},include=function(s,d){_s+=tmpl(s,d);}", "function" == typeof define && define.amd ? define(function() {
        return n
    }) : e.tmpl = n
}(this);

App = (
        function($) {


            Func = {
                // can be plugin="truncate", or handle all item when init page
                handleTruncate: function(selector) {

                    var defaults = {
                        size: 240,
                        omission: '...',
                        ignore: true
                    },
                    options = $.extend(defaults, App.getDataFromEl(selector));

                    var textDefault = selector.text(),
                            textTruncated,
                            regex = /[!-\/:-@\[-`{-~]$/;

                    if (textDefault.length > options.size) {
                        textTruncated = $.trim(textDefault).
                                substring(0, options.size).
                                split(' ').
                                slice(0, -1).
                                join(' ');
                        if (options.ignore) {
                            textTruncated = textTruncated.replace(regex, '');
                        }

                        selector.text(textTruncated + options.omission).attr('title', textDefault);
                    }

                },
                handleCalendar: function(selector) {
                    var format = selector.attr('format') ? selector.attr('format') : 'yy年mm月dd日';
                    selector.datepicker({
                        changeMonth: true,
                        changeYear: true,
                        dateFormat: format
                    });
                },
                handleUlList: function(selector) {
                    var row = selector.attr('data-row');
                    var list = selector.attr('data-list') || 'li';
                    var container = selector.attr('data-container');

                    var getContainer = function(el, container) {
                        return container ? el.find(container) : el;
                    }

                    var j = 0, newUl, temp = selector.clone(), current = selector;
                    var containerEl = getContainer(temp, container).empty();
                    var liList = getContainer(selector, container).find(list);
                    var first = true;

                    for (i = row, count = liList.size(); i < count; ++i) {
                        j++;
                        if (j == 1) {
                            newUl = temp.clone();
                            containerEl = getContainer(newUl, container);
                            newUl.find("input[display-first]").attr("display-first","no");
                            newUl.find("p[display-first]").attr("display-first","no");
                            newUl.find("div[display-first]").attr("display-first","no");
                            if(!first){
                            	//var header = $(containerEl).find("thead");
                            	//var items = new Array();
                            	//newUl.find("input[display-first]").attr("display-first","no");
                            	/*
                            	items.push(header.find("input[display-first]")[0]);
                            	items.push($(header).find("div[display-first]"));
                            	items.push($(header).find("p[display-first]"));
                            	for(var k=0;k<items.length;k++){
                            		items[k].css("display","none");
                            	}
                            	*/
                            }
                        } else if (j == row) {
                            j = 0;
                            current.after(newUl);
                            current = newUl;
                            newUl = null;
                            first = false;
                        }
                        containerEl.append(liList[i]);
                    }
                    if (newUl)
                        current.after(newUl);
                },
                handleButton: function(selector) {
                    var action = selector.attr('action');
                    if (action) {
                        selector.click(function(e) {
                            var form = selector.closest('form');
                            if (form.size()) {
                                form[0][action]();
                            }
                            return false;
                        });
                    }
                },
                handlePaginator: function(selector) {
                    if (selector.attr('remove-tag') == '1') {
                        selector.find('span:first,span:last').each(function() {
                            $(this).replaceWith($(this).html());
                        });
                    }
                    if (selector.attr('last-class'))
                        selector.find('span:last').addClass(selector.attr('last-class'));
                },
                handleLog: function(selector) {
                    selector.click(function() {
                        var content = selector.attr('content');
                        var type = selector.attr('type');
                        var url = 'pages/saveLog/';
                        $.ajax({
                            type: "POST",
                            data: {content: content, type: type},
                            url: url,
                            async: false
                        });
                    });
                }

            };

            Atc = {
                handleNumeric: function(selector, e) {
                    if (!selector.hasClass('numeric')) {
                        var data = $.extend({
                            maxPreDecimalPlaces: 9,
                            maxDecimalPlaces: 0
                        }, App.getDataFromEl(selector));
                        selector.numeric(data).addClass('numeric');
                    }
                },
                handleId: function(selector, e) {
                    if (!selector.hasClass('numeric')) {
                        var data = $.extend({
//                            maxPreDecimalPlaces: 9,
                            maxDecimalPlaces: 0
                        }, App.getDataFromEl(selector));
                        selector.numeric(data).addClass('numeric');
                    }
                },
                handlePassword: function(selector, e) {
                    if (!selector.hasClass('numeric')) {
                        var data = $.extend({
                            maxPreDecimalPlaces: 12,
                            maxDecimalPlaces: 0
                        }, App.getDataFromEl(selector));
                        selector.numeric(data).addClass('numeric');
                    }
                },
                handlePost: function(selector, e) {
                    if (!selector.hasClass('numeric')) {
                        var data = $.extend({
                        }, App.getDataFromEl(selector));
                        selector.numeric(data).addClass('numeric');
                    }
                },
                handlePhone: function(selector, e) {
                    if (!selector.hasClass('numeric')) {
                        var data = $.extend({
                        }, App.getDataFromEl(selector));
                        selector.numeric(data).addClass('numeric');
                    }
                },
                handlePost1: function(selector, e) {
                    if (!selector.hasClass('numeric')) {
                        var data = $.extend({
                            maxPreDecimalPlaces: 3,
                            maxDecimalPlaces: 0
                        }, App.getDataFromEl(selector));
                        selector.numeric(data).addClass('numeric');
                    }
                },
                handlePost2: function(selector, e) {
                    if (!selector.hasClass('numeric')) {
                        var data = $.extend({
                            maxPreDecimalPlaces: 4,
                            maxDecimalPlaces: 0
                        }, App.getDataFromEl(selector));
                        selector.numeric(data).addClass('numeric');
                    }
                },
                handleAlpha: function(selector, e) {
                    if (!selector.hasClass('alpha')) {
                        var data = $.extend({
                            disallow: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
                        }, App.getDataFromEl(selector));
                        selector.alpha(data).addClass('alpha');
                    }
                },
                handleLatin: function(selector, e) {
                    if (!selector.hasClass('alpha')) {
                        var data = $.extend({
                            allow: '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~',
                            allowOtherCharSets: false
                        }, App.getDataFromEl(selector));
                        selector.alpha(data).addClass('alpha');
                    }
                    if (!selector.hasClass('ime-off')) {
                        selector.addClass('ime-off');
                    }
                }
            };

            return {
                Func: Func,
                Act: Atc,
                _uiList: [],
                tmpl: function(id, data) {
                    return tmpl(id)(data);
                },
                _delayT: {},
                delay: function(fn, time) {
                    var time = time || 500;
                    var key = fn.toString();
                    clearTimeout(App._delayT[key]);
                    App._delayT[key] = setTimeout(fn, time);
                },
                isAllowedKeyCode: function(keyCode, ctrlKey) {
                    // Ensure that it is a number and stop the keypress
                    if ($.inArray(keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 || // Allow: Ctrl+A
                            (keyCode == 65 && ctrlKey === true) ||
                            // Allow: home, end, left, right
                                    (keyCode >= 35 && keyCode <= 39)) {
                        // let it happen, don't do anything
                        return true;
                    }

                    return false;
                },
                getDataFromEl: function(selector) {
                    var attrs, name, data = {},
                            i = 0,
                            elem = selector[0];

                    if (elem.nodeType === 1) {
                        attrs = elem.attributes;
                        for (; i < attrs.length; i++) {
                            name = attrs[i].name;
                            if (name.indexOf("data-") === 0) {
                                name = name.slice(5).replace(/^-ms-/, "ms-").replace(/-([\da-z])/gi, function(all, letter) {
                                    return letter.toUpperCase();
                                });
                                data[name] = attrs[i].value;
                            }
                        }
                    }

                    return data;

                },
                //main function to initiate template pages
                init: function(selector) {
                    $('[ui-type]', selector).each(function() {
                        var el = $(this);
                        var uiTypes = el.attr('ui-type').split(' ');
                        for (var i in uiTypes) {
                            var funcName = 'handle' + uiTypes[i].replace(/(?:^\w|-\w)/g, function(match) {
                                // can access string as array with ie version <= 7
                                return match.charAt(match.length - 1).toUpperCase();
                            });
                            if (Func[funcName]) {
                                Func[funcName](el);
                            }
                        }

                        // add to ui list
                        App._uiList.push(el);
                    });

                },
                setUp: function() {

                    if (APP_DEBUG) {
                        App.div = {
                            backdrop: $('<div/>').css({
                                position: 'fixed',
                                top: 0,
                                bottom: 0,
                                left: 0,
                                right: 0,
                                display: 'none',
                                zIndex: 9999,
                                background: '#222'
                            }),
                            loading: $('<div/>').css({
                                position: 'fixed',
                                top: 20,
                                right: 50,
                                zIndex: 10000,
                                display: 'none'
                            }),
                            errorContainer: $('<div/>').css({
                                position: 'fixed',
                                bottom: 0,
                                left: 0,
                                width: '100%',
                                maxHeight: '100%',
                                overflow: 'auto',
                                background: '#000',
                                color: '#eee',
                                zIndex: 99,
                                // turn on debug here
                                //display: 'block'
                                // turn off debug here
                                display: 'none'

                            }),
                            errorContent: $('<div/>'),
                            errorClear: $('<div/>').css({
                                float: 'right',
                                padding: '5px',
                                lineHeight: '10px',
                                fontSize: '16px',
                                fontWeight: 'bold',
                                cursor: 'pointer',
                                overflow: 'auto',
                                background: '#000',
                                color: '#fff'
                            }).text('-')
                        };
                        App.div.errorClear.appendTo(App.div.errorContainer);
                        App.div.errorContent.appendTo(App.div.errorContainer);
                        App.div.errorContainer.appendTo('body');

                        App.div.backdrop.appendTo('body');
                        App.div.backdrop.css('opacity', '0.7');
                        App.div.loading.appendTo('body');
                        App.div.loading.html('<img src="img/loading.gif" />');

                        App.div.errorClear.toggle(function() {
                            $(this).html('+');
                            App.div.errorContent.fadeOut();
                        }, function() {
                            $(this).html('-');
                            App.div.errorContent.fadeIn();
                        });

                    }

                    $.ajaxSetup({
                        beforeSend: function() {
                            // show gif here, eg:
                            App.div.backdrop.show();
                            App.div.loading.show();
                        },
                        complete: function() {
                            // hide gif here, eg:
                            App.div.backdrop.hide();
                            App.div.loading.hide();
                        },
                        error: function(jqXHR, textStatus, errorThrown) {
                            if (APP_DEBUG) {
                                App.div.errorContent.append(textStatus);
                            }
                        },
                        dataFilter: function(data, type) {
                            if (type == 'json') {

                                var json = data.replace(/<pre[^>]*>([\s\S]*)?<\/pre>/g, function(m, g1) {
                                    //console.log(g1); // should append into debug
                                    if (APP_DEBUG) {
                                        App.div.errorContent.html(m);
                                    }
                                    return ''; // empty
                                });

                                if (!/^\s*{/.test(json)) {
                                    if (APP_DEBUG) {
                                        App.div.errorContent.append(json);
                                    }
                                }

                                // handle again ?
                                return json;

                            }

                            return data;
                        }
                    });
                },
                toJSON: function(object) {
                    if (typeof JSON.stringify !== 'function') {
                        escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
                        meta = {// table of character substitutions
                            '\b': '\\b',
                            '\t': '\\t',
                            '\n': '\\n',
                            '\f': '\\f',
                            '\r': '\\r',
                            '"': '\\"',
                            '\\': '\\\\'
                        };
                        JSON.stringify = function(value, replacer, space) {

                            // The stringify method takes a value and an optional replacer, and an optional
                            // space parameter, and returns a JSON text. The replacer can be a function
                            // that can replace values, or an array of strings that will select the keys.
                            // A default replacer method can be provided. Use of the space parameter can
                            // produce text that is more easily readable.

                            var i;
                            gap = '';
                            indent = '';

                            // If the space parameter is a number, make an indent string containing that
                            // many spaces.

                            if (typeof space === 'number') {
                                for (i = 0; i < space; i += 1) {
                                    indent += ' ';
                                }

                                // If the space parameter is a string, it will be used as the indent string.

                            } else if (typeof space === 'string') {
                                indent = space;
                            }

                            // If there is a replacer, it must be a function or an array.
                            // Otherwise, throw an error.

                            rep = replacer;
                            if (replacer && typeof replacer !== 'function' &&
                                    (typeof replacer !== 'object' ||
                                            typeof replacer.length !== 'number')) {
                                throw new Error('JSON.stringify');
                            }

                            // Make a fake root object containing our value under the key of ''.
                            // Return the result of stringifying the value.

                            return str('', {'': value});
                        };
                    }

                    return JSON.stringify(object);
                }

            };




        })(jQuery);



//for all

        (function($) {

            $.fn.serializeObject = function() {
                // must be include without ajax
                "use strict";

                var result = {};
                var extend = function(i, element) {
                    var node = result[element.name];

                    // If node with same name exists already, need to convert it to an array as it
                    // is a multi-value field (i.e., checkboxes)

                    if ('undefined' !== typeof node && node !== null) {
                        if ($.isArray(node)) {
                            node.push(element.value);
                        } else {
                            result[element.name] = [node, element.value];
                        }
                    } else {
                        result[element.name] = element.value;
                    }
                };

                $.each(this.serializeArray(), extend);
                return result;
            };

            $(function() {
                App.setUp();
                App.init('body');

                // setup closure for action on all elements,
                // remove load and unload because: load and unload can be hook by ui-type
                // and it will reduce time for checking all element before rendering
                $(document).bind("blur focus resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error", function(e) {
                    var el = $(e.target);
                    var actType = el.attr('act-type');
                    if (actType) {
                        var uiActs = actType.split(' ');
                        for (var i in uiActs) {
                            var temp = uiActs[i].split(':'), eName = temp[0], fName = temp[1];
                            if (e.type === eName) {
                                var funcName = 'handle' + fName.replace(/(?:^\w|-\w)/g, function(match) {
                                    // can access string as array with ie version <= 7
                                    return match.charAt(match.length - 1).toUpperCase();
                                });
                                if (App.Act[funcName]) {
                                    App.Act[funcName](el, e);
                                }
                            }
                        }

                        // add to action list
                    }

                });

            });
        })(jQuery);

